<?php
/**
 * Created by PhpStorm.
 * User: aoc
 * Date: 2018/6/21
 * Time: 8:17
 */

namespace app\api\controller\v2\model\Coupon;


use think\Model;
use think\Db;

/**
 * 优惠券业务处理类
 * Class Coupon
 * @package app\api\controller\v1\model\Coupon
 */
class Coupon extends Model
{

    /**
     * 查询用户拥有某种优惠券数目
     * @param $user_id      用户id
     * @param $coupon_id    优惠券id
     * @return array
     */
    public function search_coupon($user_id,$coupon_id)
    {
        try {
            //从ym_user_to_coupon中查询用户有多少张代金券
            $count = Db::table('ym_user_to_coupon')->where('user_id = :user_id and coupon_id = :coupon_id')->bind(['user_id' => $user_id, 'coupon_id' => $coupon_id])->find();
        }catch(\Exception $e)
        {
            return ['status'=>false,'message'=>$e->getMessage()];
        }
        if($count)
        {
            return ['status'=>true,'message'=>'操作成功','data'=>$count];
        }
            return ['status'=>false,'message'=>'数据库查询为空'];
    }

    /**
     * 操作数据库，修改用户代金券数量，修改代金券本身状态
     * @param $user_id  用户id
     * @param $to_id  用户对应代金券表的 id
     * @return array
     */
    public function consume_coupon($user_id,$to_id)
    {
        //操作ym_cash_coupon_list表，查询更新数据
        Db::startTrans();
        try{
            $cash_cpon = [];
            //操作ym_user_to_coupon 更新用户代金券数量
            $cash_cpons = Db::table('ym_cash_coupon_list')->where('user_id = :user_id and status = :status')->bind(['user_id'=>$user_id, 'status'=> 1])->select();
            if(!$cash_cpons)
            {
                return ['status'=>false,'message'=>'数据库查询为空'];
            }
            foreach($cash_cpons as $cash_cp)
            {
                //找到没有超过有效期
                if($cash_cp['period_of_validity'] >= $cash_cp['create_time'])
                {
                    $cash_cpon = $cash_cp;
                    break;
                }
            }
            //将有效的代金券变为无效的，将用户可用代金券数减一
            $c_res = Db::table('ym_cash_coupon_list')->where('id','=',$cash_cpon['id'])->update(['status' => 0]);
            $u_res = Db::table('ym_user_to_coupon')->where('id','=',$to_id)->setDec('used_amount');
            if(!$c_res || !$u_res)
            {
                return ['status'=>false,'message'=>'更新失败'];
            }
            Db::commit();
        }catch(\Exception $e)
        {
            Db::rollback();
            return ['status'=>false,'message'=>$e->getMessage()];
        }
        return ['status'=>true,'message'=>'更新成功'];
    }

    /**
     *  赠送代金券
     * @param $user_id  用户id
     * @param $coupon_id    优惠券类型 1为代金券
     * @param int $count  赠送的数目
     * @return array
     */
    public function handsel_coupon($user_id,$coupon_id=1,$count=3)
    {
        //操作表，查询更新数据
        Db::startTrans();
        try{
            //多字节自增
            Db::query("update ym_user_to_coupon set amount=amount+$count,used_amount=used_amount+$count where user_id = $user_id and coupon_id = $coupon_id");
            //关联表添加完了，就可以添加另一个表
            $add_data = [];
            for($i=0;$i<$count;$i++)
            {
                $param = [
                    'user_id' => $user_id,
                    'code' => self::build_code($lenght = 16),
                    'coupon_id' => $coupon_id,
                    'use_range' => 999, //默认999为全局app使用
                    'period_of_validity' => date('2078-01-01 00:00:00')  //默认到2099年
                ];
                $add_data[] = $param;
            }
            //向cash_coupon_list中添加相应数据
            $add_res = Db::name('ym_cash_coupon_list')->insertAll($add_data);
            if(!$add_res)
            {
                return ['status'=>false,'message'=>'更新失败'];
            }
            Db::commit();
        }catch(\Exception $e)
        {
            Db::rollback();
            echo $e->getMessage();
            return ['status'=>false,'message'=>$e->getMessage()];
        }
        return ['status'=>true,'message'=>'更新成功'];
    }

    /**
     * 注册添加用户代金券关联表
     * @param $user
     * @param int $coupon_id
     * @param int $amount
     * @param int $used_amount
     */
    public function add_user_to_coupon($user_id, $coupon_id=1, $amount=0, $used_amount=0)
    {
        try{
            $data = [
                'user_id' => $user_id,
                'coupon_id' => $coupon_id,
                'amount' => $amount,
                'used_amount' => $used_amount
            ];
            $result = Db::name('ym_user_to_coupon')->insert($data);
            if($result)
            {
                return ['status'=>true,'message'=>'更新成功'];
            }

        }catch(\Exception $e)
        {
            return ['status'=>false,'message'=>$e->getMessage()];
        }
        return ['status'=>false,'message'=>'更新失败'];
    }

    /**
     * 消耗宠粮兑换粮票
     * @param $user_id  用户id
     * @param $pet_food_id  宠粮id
     * @param $num  兑换数目
     * @return array
     */
    public function exchange_cash_coupon($user_id, $pet_food_id, $num)
    {
        //操作表，查询更新数据
        Db::startTrans();
        try{
            //扣除ym_pet_food表中的宠粮
            $del_pet = Db::table('ym_pet_food')->where('pet_food_id','=',$pet_food_id)->setDec('pet_food', $num * 30);
            if(!$del_pet)
            {
                return ['status'=>false,'message'=>'更新失败'];
            }
            //添加代金券和用户未使用代金券的数目
            $result = $this->handsel_coupon($user_id,1,$num);
            if(!$result['status'])
            {
                return ['status'=>false,'message'=>'更新失败'];
            }
            Db::commit();
        }catch(\Exception $e)
        {
            Db::rollback();
            return ['status'=>false,'message'=>$e->getMessage()];
        }
        return ['status'=>true,'message'=>'更新成功'];
    }

    /**
     * 个人登录状态
     * @param $user_id
     * @return mixed
     */
    public static function get_user_status($user_id)
    {
        $result = Db::query("SELECT `login_status` FROM ym_user WHERE id = '$user_id'");
        return $result[0];
    }

    /**
     * 生成AccessToken
     * @return string
     */
    public static function build_code($lenght = 16)
    {
        //生成代金券code值
        $str_pol = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyz";
        return substr(str_shuffle($str_pol), 0, $lenght);
    }

    /**
     * 拿到该用户的宠粮数
     * @param $user_id
     * @return mixed
     */
    public static function get_pet_food($user_id){
        $result = Db::query("select pet_food from ym_pet_food where user_id = '$user_id'");
        $pet_food = $result[0];
        return $pet_food;
    }


}